<template>
  <div>
    <TopFilter
      ref="topFilter"
      :list="topFilterList"
      :cols="3"
      labelWidth="90"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>

    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :onRowSelectChange="selectChange"
      :onSyncTableData="tableDataChange"
      :onColumnsChange="columns => this.columns = columns"
    >
      <template slot="controls">
        <!-- <el-button :disabled="isChoice" size="small" type="primary" icon="el-icon-plus" @click="redistribution">再分配</el-button> -->
        <multiuse-button :disabled="isChoice" size="small" type="primary" icon="el-icon-plus" :click="redistribution" :auth-list="auths" auth-mark="/api/cyxdms.customercare/careTask/careTasks/modifyCareTaskEmp">再分配</multiuse-button>
      </template>
    </FilterTable>

    <Drawer
      :visible.sync="visible"
      :title="'关爱任务明细'"
      :width="1100"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <careObjDetail :type="handleType" :rowData="rowData" @changeHandle="changeHandle" @close="closeHandler" />
    </Drawer>

    <BaseDialog
      :visible.sync="visible2"
      :title="'关爱任务再分配'"
      destroyOnClose
      width='30%'
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <redistribution :careTaskIds="careTaskIds" @changeHandle="changeHandle" @close="closeHandler" />
    </BaseDialog>
  </div>
</template>
<script>
import {
  getCareTaskList,
  modifyCareTaskStatus,
  getUserInfoByRole,
  getUserInfo
} from '@/api/customerCare/saleVisit/careTaskSearch';
import { dictionary } from '@/utils/dictMixin';
import careObjDetail from './careObjDetail';
import redistribution from './redistribution';

import { authority } from '@/utils/authMixin';
export default {
  name: 'CarTaskSearch',
  mixins: [dictionary,authority],
  components: {careObjDetail,redistribution},
  data(){
    return {
      topFilterList: this.createTopFilters(),
      columns: this.createTableColumns(),
      fetchApi: getCareTaskList,
      fetchParams: {},
      handleType: 'show',
      selectedRows: [],
      rowData: {},
      careTaskIds: [],
      isChoice: true,
      visible: false,
      visible2: false
    }
  },
  methods: {
    createTopFilters(){
      return [
        {
          type: 'SELECT',
          label: '关爱类型',
          fieldName: 'careTypeCode',
          placeholder: '请选择...',
          itemList: this.createDictList('1572')
        },
        {
          type: 'INPUT',
          label: '关爱名称',
          fieldName: 'careName',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '关爱人员',
          fieldName: 'employeeId',
          placeholder: '请选择...',
          itemList: this.createdEmpList()
        },
        {
          type: 'SELECT',
          label: '是否关闭',
          fieldName: 'whetherClose',
          placeholder: '请选择...',
          itemList: this.createDictList('1004')
        },
        {
          type: 'RANGE_DATE',
          label: '分配日期',
          fieldName: 'distributeStart|distributeEnd',
          placeholder: '分配日期'
        },
        {
          type: 'RANGE_DATE',
          label: '要求完成日期',
          fieldName: 'requiredDateStart|requiredDateEnd',
          placeholder: '要求完成日期'
        },
        {
          type: 'SELECT',
          label: '是否完成',
          fieldName: 'whetherFinish',
          placeholder: '请选择...',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '分配方式',
          fieldName: 'distributeWay',
          placeholder: '请选择...',
          itemList: this.createDictList('1586')
        }
      ]
    },
    createTableColumns(){
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          width: 90,
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" divider="after" disabled={props.row.isClose==10041001} type="text" onClick={() => this.closeCare(props.row)} auth-list={this.auths} auth-mark={'/api/cyxdms.customercare/careTask/careTasks/modifyCareTaskStatus'}>
                  关闭
                </multiuse-button>
                <el-button size="mini" type="text" onClick={() => this.showHandler(props.row)}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '任务编号',
          dataIndex: 'taskNo',
          width: 125,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '关爱类型',
          dataIndex: 'careTypeCode',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.careTypeCode, '1572')}</div>;
          }
        },
        {
          title: '关爱名称',
          dataIndex: 'careName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '分配日期',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '要求完成日期',
          dataIndex: 'requiredDate',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '关爱人员',
          dataIndex: 'employeeName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '任务数',
          dataIndex: 'taskCount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '完成数',
          dataIndex: 'finishCount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '剩余数',
          dataIndex: 'num3',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return props.row.taskCount - props.row.finishCount;
          }
        },
        {
          title: '分配方式',
          dataIndex: 'distributeWay',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.distributeWay, '1586')}</div>;
          }
        },
        {
          title: '计划编号',
          dataIndex: 'planNo',
          width: 125,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '是否关闭',
          dataIndex: 'isClose',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.isClose, '1004')}</div>;
          }
        }
      ]
    },
    redistribution(){
      let params = [];
      this.selectedRows.map(obj=>{
        params.push(obj.careTaskId);
      });
      this.careTaskIds = params;
      this.visible2 = true;
    },
    createdEmpList(){
      //初始化关爱人员选择列表
      getUserInfo().then(res => {
        if(res.resultCode == 200){
          let param = {
            companyId:res.data.userInfo.companyId,
            positionCode:"10061010"
          };
          getUserInfoByRole(param).then(res => {
            if(res.resultCode == 200){
              this.topFilterList.find(item=>item.fieldName==='employeeId').itemList = res.data.map(x => ({ value: x.userId, text: x.employeeName }))
            }else{
              this.$message.error('获取关爱人员列表失败!');
            }
          })
        }else{
          this.$message.error('获取当前登录用户信息失败!');
        }
      })
    },
    closeCare(row){
      this.$confirm('是否确认关闭?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        modifyCareTaskStatus(row.careTaskId).then(res => {
          if (res.resultCode == 200) {
            this.$message.success('关闭成功');
            this.fetchParams = { ...this.fetchParams };
          }else{
            this.$message.error(res.data.errMsg);
          }
        });
      }).catch(() => {});
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    tableDataChange (data, isFirst) {
      if (isFirst) {
        let disabledSelect = data.filter(row => row.isClose=== 10041001)
        this.$refs.table.$refs.pageTable.SET_DISABLE_SELECT(disabledSelect)
      }
    },
    selectChange (rows){ //选中时触发的函数
      this.selectedRows = rows;
      this.isChoice = this.selectedRows.length > 0? false: true;
    },
    changeHandle(val) {
      if(val.distributeStart&&val.distributeStart!=''){
        val.distributeStart = val.distributeStart.substring(0,10);
      }
      if(val.distributeEnd&&val.distributeEnd!=''){
        val.distributeEnd = val.distributeEnd.substring(0,10);
      }
      if(val.requiredDateStart&&val.requiredDateStart!=''){
        val.requiredDateStart = val.requiredDateStart.substring(0,10);
      }
      if(val.requiredDateEnd&&val.requiredDateEnd!=''){
        val.requiredDateEnd = val.requiredDateEnd.substring(0,10);
      }
      this.fetchParams = Object.assign({}, val);
    },
    showHandler(row) {
      this.visible = true;
      this.rowData = row;
    },
    closeHandler() {
      this.visible = false;
      this.visible2 = false;
    }
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  }
}
</script>
